<template>
  <div class="goods-list-main">
    <!-- 搜索 -->
    <div class="search-area v-align-c">
      <div class="search-box flex">
        <el-select v-model="searchListQuery.searchKeyWordType">
          <el-option label="商品名称" value="1"></el-option>
        </el-select>
        <el-input v-model="searchListQuery.searchKeyWord" @keyup.enter.native="handleSearch" placeholder="请输入商品名称"></el-input>     
      </div>    
      <div>
          <label class="mar-l-20">跨境类型：</label>
          <el-select v-model="searchListQuery.crossBorderType">
            <el-option label="全部" value=""></el-option>
            <el-option label="普通商品" value="1"></el-option>
            <el-option label="跨境保税" value="2"></el-option>
          </el-select>
      </div>
      <div class="font-14 clear-input-btn mar-l-24 v-align-c pointer" @click="resetSearch">
        <i class="el-icon-refresh font-18"></i>
        <span class="mar-l-4">清除筛选条件</span>
      </div>
      <div class="font-14 result-info font-white mar-l-27">
        <span class="font-w">{{resultNum}}</span>
        <span>条结果</span>
      </div>
      <el-button type="primary" @click="handleSearch">搜索</el-button> 
      
    </div>
    <!-- 搜索条件区域 -->
    <div class="form-area mar-t-20 flex-between">
      <!-- 表单 -->
      <el-form ref="form" :model="formData" :inline="true">
        <el-form-item label="商品分类">
          <el-cascader style="width: 110px" v-model="categoryIds" :props="{ checkStrictly: true }" change-on-select
            placeholder="全部" :options="categoryData" class="default-input" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="供货价" class="mar-l-28">
          <el-input v-model="searchListQuery.supplyAlliancePrice" style="width: 80px" placeholder="最小"></el-input>
          <span>元-</span>
          <el-input v-model="searchListQuery.supplyAllianceMaxPrice" style="width: 80px" placeholder="最大"></el-input>
          <span>元</span>
        </el-form-item>
        <el-form-item label="利润率" class="mar-l-28">
          <el-input v-model="searchListQuery.supplyAllianceProfitMargin" style="width: 80px" placeholder="最小">
          </el-input>
          <span>%-</span>
          <el-input v-model="searchListQuery.maxSupplyAllianceProfitMargin" style="width: 80px" placeholder="最大">
          </el-input>
          <span>%</span>
        </el-form-item>
        <el-form-item label="添加状态:" class="mar-l-30">
          <div class="flex">
            <div @click="changeStatus(index)" class="status-btn font-14 flex-center width-76 height-32 mar-l-9 pointer"
              v-for="(item, index) in status" :key="index"
              :class="index === statusIndex ? 'active-btn':'disactive-btn'">
              {{item}}
            </div>
          </div>
        </el-form-item>
        <!--<el-checkbox v-model="formData.checked" class="mar-l-28">包邮</el-checkbox>-->
        <!-- <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="initGoodsList">查询</el-button> -->
      </el-form>
      <!-- tab切换 -->
      <div class="tab-btn-area v-align-c font-14">
        <span class="mar-r-20">列表排序：</span>
        <ul class="flex">
          <li v-for="(item, index) of tabBtn" :key="index" :class="activeTabBtn === index ? 'active-tab': ''"
            @click="handleClick(index)">{{item}}</li>
        </ul>
      </div>
    </div>
    <!-- 列表区域 -->
    <div class="list-box mar-t-10" v-if="goodsList.length > 0">
      <!-- 列表-->
      <div class="list-info">
        <!-- 商品列表 -->
        <div class="list-data-box">
          <el-row :gutter="20" style="display: flex;flex-wrap: wrap;">
            <el-col :span="4" ref="elCol" v-for="(item, index) in goodsList" :key="index"
              @click.native.stop="selectGoods(item)" @mouseenter.native="mouseEenter(index)"
              @mouseleave.native="mouseLeave" style="cursor: pointer">
              <div :class=" currentGoodsIndex === index ? 'item-active' : 'item-dis'" class="list-item">
                <div class="list-img-box" ref="imgBox">
                  <div v-if="item.crossBorderType === 2">
                    <img :src="item.picUrl" alt="" />
                    <img :src="crossBorderLabel2" alt="" class="pic-sup"/>
                  </div>
                  <div v-else><img :src="item.picUrl" alt="" /></div>
                  <!-- <el-image style="height: 263px" :src="item.picUrl" :fit="fit"></el-image> -->
                  <p class="sales">销量 {{ item.salesNum }} 件</p>
                  <!-- <p :class="currentGoodsIndex === index ? 'sales-active' : 'sales-dis'" class="sales">销量 {{ item.salesNum }}</p> -->
                </div>
                <div class="list-text-box">
                  <el-tooltip class="item" effect="light" :content="item.title" placement="top-start">
                    <span class="line-2 mar-b-29" style="height:38px">{{ item.title }}</span>
                  </el-tooltip>
                  <span class="line-1">供货价 <span class="cost-price">￥{{item.supplyAlliancePrice}}</span>
                    <span v-if="item.supplyAllianceMaxPrice && item.supplyAlliancePrice != item.supplyAllianceMaxPrice"
                      class="cost-price">~
                      ￥{{item.supplyAllianceMaxPrice}}</span>
                  </span>
                  <span>利润率
                    <span class="red-font">{{item.supplyAllianceProfitMargin || 0.00}}%</span>
                    <span class="red-font"
                      v-if="item.maxSupplyAllianceProfitMargin != null && item.maxSupplyAllianceProfitMargin > 0 && item.supplyAllianceProfitMargin !== item.maxSupplyAllianceProfitMargin">~
                      {{item.maxSupplyAllianceProfitMargin}}%</span>
                  </span>
                </div>
                <div class="add-btn-box">
                  <div class="addBtn" v-if="item.supplyAllianceIsJoinSelectionStatus === 0">
                    <el-button :loading="isAddToStoreLoading"
                      style="width: 70%;background: #ff5a00;color: white;border: 0.5 solid #ff5a00;"
                      @click.stop="addToStore(item)">添加到仓库</el-button>
                  </div>
                  <div class="addBtn" v-if="item.supplyAllianceIsJoinSelectionStatus === 1">
                    <span style="color:#ff5a00" class="pad-t-4 pad-b-4">已添加到仓库</span>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <!-- 列表分页 -->
        <div class="pagination">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="searchListQuery.currentPage" :page-sizes="[12, 24, 60, 96]" :page-size="searchListQuery.size"
            layout="prev, pager, next" :total="total">
          </el-pagination>
        </div>
      </div>
    </div>
    <div class="align-c no-data-box mar-t-20" v-else>
      <span class="font-20" style="color:#5E5E60">暂无数据</span>
      <img class="width-233 height-138" :src="noDataPic" alt="" style="margin-top:30px">
    </div>
    <!--关联企业分类-->
    <div class="dialog-sort">
      <el-dialog width="500px" title="请关联企业分类" :visible.sync="dialogVisible"  :show-close="false">
        <div class="text-align-c pad-t-20 pad-b-30">
          <el-cascader style="width: 200px" v-model="enCategoryIds" :props="{ checkStrictly: true }" change-on-select
            placeholder="选择商品分类" :options="enCategoryList" class="default-input" clearable></el-cascader>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCloseSelectCategory">取消</el-button>
          <el-button :loading="isAddToStoreLoading" type="primary" @click="onSetCategory">确定</el-button>
        </div>
      </el-dialog>
    </div>

    <div v-if="dialogGoodsInfo">
      <goods-detail :goodsId="selectGoodsId"
        :supplyAllianceIsJoinSelectionStatus="currentSupplyAllianceIsJoinSelectionStatus"
        :isAddToStoreLoading="isAddToStoreLoading" @closeGoodsDeatil="closeGoodsDeatil" @addToStore="addToStore">
      </goods-detail>
    </div>
  </div>
</template>


<script>
  import {
    pagingSupplyAllianceGoodsList,
    saveJoinProjectGoods
  } from '@/api/goods/supplyAlliance'
  import {
    getProjectCategoryTree
  } from '@/api/project/projectGoodsCategory'
  import {
    listGoodsCategory
  } from '@/api/goods/goods'
  import noDataPic from '../../../../assets/images/no-data.png'
  import GoodsDetail from '../components/GoodsDetail/index'
  import crossBorderLabel2 from '@/assets/images/cross-border-label-2.png'
  export default {
    components: {
      GoodsDetail
    },
    data() {
      return {
        noDataPic: noDataPic,
        total: null,
        listLoading: false,
        dialogVisible: false,
        selectSortType: '1',
        goodsList: [],
        categoryIds: [],
        categoryData: [],
        enCategoryList: [],
        enCategoryIds: [],
        enterpriseCategoryId: '',
        selectGoodsId: '', // 选择的商品id
        warehouseType: '',
        formData: {
          goodsSort: '', // 商品分类
          warehouseStatus: '', // 选择仓库状态
          costPrice: {
            price1: '',
            price2: ''
          }, // 供货价
          checked: false // 包邮
        },
        searchListQuery: {
          notInSupplyAllianceEnterpriseId: this.getEnterpriseId(),
          page: 1,
          size: 12,
          ascs: '',
          descs: '',
          supplyAlliancePrice: '',
          supplyAllianceMaxPrice: '',
          selectSortType: '1',
          searchKeyWordType: '1',
          searchKeyWord: '',
          crossBorderType: '',
          supplyAllianceOneCategoryId: '',
          supplyAllianceStatusList: '1',
          goodsSourceList: '0,1',
          isNeedCalSupplyAllianceProfitMargin: 1,
          // 传-1的目的是因为查询全部也要判断状态，其他场景放空就不会去查询
          supplyAllianceIsJoinSelectionStatus: -1
        },
        crossBorderLabel2: crossBorderLabel2,
        currentGoodsIndex: '', // 当前点击的商品索引
        tabBtn: ['按利润', '按供货价', '按销量', '按上架时间'],
        activeTabBtn: 0,
        searchCondition: '1', // 1：通过商品名称搜索 / 2：通过店铺名称搜索
        dialogGoodsInfo: false,
        status: ['全部', '已加入仓库', '未加入仓库'],
        statusIndex: 0,
        resultNum: 0,
        isAddToStoreLoading: false,
        currentSupplyAllianceIsJoinSelectionStatus: 0
      }
    },
    // 初始化页面
    created() {
      this.initGoodsList()
      this.getProjectCategoryTree()
    },
    mounted() {},
    methods: {
      getProjectCategoryTree() {
        getProjectCategoryTree().then(response => {
          this.categoryData = response.data
        })
      },
      changeStatus(index) {
        if (this.statusIndex === index) return
        this.statusIndex = index
        switch (index) {
          case 0:
            index = '-1'
            break
          case 1:
            index = 1
            break
          case 2:
            index = 0
            break
        }
        this.searchListQuery.supplyAllianceIsJoinSelectionStatus = index
        this.searchListQuery.currentPage = 1
        this.initGoodsList()
      },
      onSetCategory() {
        if (this.enCategoryIds === '' || this.enCategoryIds.length === 0) {
          this.$message.error('请选择要关联的分类')
          return
        }
        if (this.enCategoryIds.length === 1) {
          this.enterpriseCategoryId = this.enCategoryIds[0]
        }
        if (this.enCategoryIds.length === 2) {
          this.enterpriseCategoryId = this.enCategoryIds[1]
        }
        if (this.enCategoryIds.length === 3) {
          this.enterpriseCategoryId = this.enCategoryIds[2]
        }
        this.saveJoin()
      },
      resetSearch() {
        this.categoryIds = []
        this.title = ''
        this.selectSortType = '1'
        this.statusIndex = 0
        this.searchListQuery = {
          notInSupplyAllianceEnterpriseId: this.getEnterpriseId(),
          page: 1,
          size: 12,
          ascs: '',
          descs: '',
          supplyAlliancePrice: '',
          supplyAllianceMaxPrice: '',
          selectSortType: '1',
          searchKeyWordType: '1',
          searchKeyWord: '',
          crossBorderType: '',
          supplyAllianceOneCategoryId: '',
          supplyAllianceStatusList: '1',
          goodsSourceList: '0,1',
          isNeedCalSupplyAllianceProfitMargin: 1,
          supplyAllianceProfitMargin: undefined,
          maxSupplyAllianceProfitMargin: undefined,
          // 传-1的目的是因为查询全部也要判断状态，其他场景放空就不会去查询
          supplyAllianceIsJoinSelectionStatus: -1
        }
        this.initGoodsList()
      },
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initGoodsList()
      },
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initGoodsList()
      },
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.initGoodsList()
      },
      initGoodsList() {
        // this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.selectSortType = this.selectSortType
        const projectCategoryIds = this.categoryIds
        if (projectCategoryIds) {
          if (projectCategoryIds.length === 1) {
            this.searchListQuery.supplyAllianceOneCategoryId = projectCategoryIds[0]
          }
          if (projectCategoryIds.length === 2) {
            this.searchListQuery.supplyAllianceOneCategoryId = projectCategoryIds[0]
            this.searchListQuery.supplyAllianceTwoCategoryId = projectCategoryIds[1]
          }
          if (projectCategoryIds.length === 3) {
            this.searchListQuery.supplyAllianceOneCategoryId = projectCategoryIds[0]
            this.searchListQuery.supplyAllianceTwoCategoryId = projectCategoryIds[1]
            this.searchListQuery.supplyAllianceThreeCategoryId = projectCategoryIds[2]
          }
        }
        if (this.searchListQuery.supplyAlliancePrice) {
          if (!this.$utils.isPrice(this.searchListQuery.supplyAlliancePrice)) {
            this.$message.error('请输入正确的最小供货价!')
            return false
          }
        }
        if (this.searchListQuery.supplyAllianceMaxPrice) {
          if (!this.$utils.isPrice(this.searchListQuery.supplyAllianceMaxPrice)) {
            this.$message.error('请输入正确的最大供货价!')
            return false
          }
        }
        if (this.searchListQuery.supplyAlliancePrice) {
          if (!this.$utils.isPrice(this.searchListQuery.supplyAlliancePrice)) {
            this.$message.error('请输入正确的最小供货价!')
            return false
          }
        }
        if (this.searchListQuery.supplyAllianceProfitMargin) {
          if (!this.$utils.isPrice(this.searchListQuery.supplyAllianceProfitMargin)) {
            this.$message.error('请输入正确的最小利润率!')
            return false
          }
        }
        if (this.searchListQuery.maxSupplyAllianceProfitMargin) {
          if (!this.$utils.isPrice(this.searchListQuery.maxSupplyAllianceProfitMargin)) {
            this.$message.error('请输入正确的最大利润率!')
            return false
          }
        }
        this.loading = this.$loading({
          lock: true,
          text: '加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        pagingSupplyAllianceGoodsList(this.searchListQuery).then((response) => {
          this.loading.close()
          if (response.isError) return
          this.listLoading = false
          this.total = response.total
          this.resultNum = response.total > 99 ? '99+' : response.total
          this.goodsList = response.records
          this.goodsList.forEach(item => {
            const img = new Image()
            img.src = `${item.picUrl}?imageView2/1/w/260/h/260/q/100`
            item.picUrl = `${item.picUrl}?imageView2/1/w/260/h/260/q/100`
          })
        })
      },
      addToStore(row) {
        // console.log(999)
        // console.log(row)
        // this.platCategoryId = row.categoryId
        this.selectGoodsId = row.goodsId
        this.saveJoin()
      },
      saveJoin() {
        this.isAddToStoreLoading = true
        // const loading = this.$loading({
        //   lock: true,
        //   text: '添加商品中...',
        //   spinner: 'el-icon-loading',
        //   background: 'rgba(0, 0, 0, 0.7)'
        // })
        saveJoinProjectGoods(this.selectGoodsId, this.getEnterpriseId(), this.enterpriseCategoryId).then(response => {
          this.enterpriseCategoryId = ''
          this.isAddToStoreLoading = false
          // loading.close()
          if (response.isError) return
          if (response.data === true) {
            this.$message({
              message: '成功',
              type: 'success'
            })
            this.dialogVisible = false
            this.currentSupplyAllianceIsJoinSelectionStatus = 1
            this.initGoodsList()
            return
          } else {
            this.listGoodsCategory()
          }
        })
      },
      // 切换tabs 标签
      handleClick(index) {
        this.activeTabBtn = index
        this.selectSortType = (index + 1)
        this.initGoodsList()
      },
      // 点击列表中的商品
      selectGoods(row) {
        // const routeData = this.$router.resolve({
        //   path: '/goods/taobao-goods/detail/index',
        //   query: { itemId: row.itemId }
        // })
        // window.open(routeData.href, '_blank')
        this.selectGoodsId = row.goodsId
        this.currentSupplyAllianceIsJoinSelectionStatus = row.supplyAllianceIsJoinSelectionStatus
        this.dialogGoodsInfo = true
      },
      closeGoodsDeatil() {
        this.dialogGoodsInfo = false
      },
      // 获取类目
      listGoodsCategory() {
        const enterpriseId = this.getEnterpriseId()
        listGoodsCategory(enterpriseId).then(response => {
          this.enCategoryList = response.data
          this.dialogVisible = true
        })
      },
      mouseEenter(index) {
        this.currentGoodsIndex = index
      },
      mouseLeave() {
        this.currentGoodsIndex = ''
      },
      handleCloseSelectCategory() {
        this.dialogVisible = false
        this.enCategoryIds = []
        this.enterpriseCategoryId = ''
      }
    }
  }
</script>

<style scoped lang="less">
  .goods-list-main {
    min-height: 100vh;
    background-color: white;

    // padding: 24px;
    // background: #f7f9fb;
    .search-area {
      height: 100%;

      .pointer:hover {
        cursor: pointer
      }

      .search-box {
        width: 552px;

        /deep/ .el-button {
          border-radius: 0px;
        }

        /deep/ .el-button--medium {
          border-radius: 0px;
        }

        /deep/ .el-input__inner {
          border-radius: 0px;
        }
      }

      .clear-input-btn {
        color: #1072CD;
      }

      .result-info {
        &>span:nth-child(1) {
          color: #FF9000;
        }
      }
    }

    .form-area {

      /deep/ .el-input__inner {}

      /deep/ .el-form-item {
        margin-bottom: 0px;
      }

      /deep/ .el-form-item__label {}

      .active-btn {
        background: #0A89FF;
        color: #fff;
      }

      .disactive-btn {
        border: 1px solid #DCDFE6;

      }
    }

    .tab-btn-area {
      ul {
        list-style: none;
        padding: 0px;
        margin: 0;

        li {
          cursor: Pointer;
        }

        li:not(:first-child) {
          margin-left: 45px;
        }

        .active-tab {
          color: #0A89FF;
          border-bottom: 2px solid #0A89FF;
        }

      }
    }

    .list-box {
      /deep/ .el-tabs__nav {

        .is-active {}

        .el-tabs__item {
          margin-right: 0 !important;
        }
      }

      .list-info {
        .el-pagination {
          text-align: center;
          margin-top: 40px;
          margin-bottom: 40px;
        }
      }

      .list-data-box {
        .el-col {
          margin-top: 10px;
        }

        .item-active {
          border: 1px solid #ff5a00;
          // height: 406px;
        }

        .item-dis {
          border: 1px solid #252529;
          // height: 406px;
        }

        .list-item {
          position: relative;

          .list-img-box {
            position: relative;

            img {
              width: 100%;
              height: 260px;
              display: block;
            }

            .sales-active {}

            .sales-dis {
              background: rgba(0, 0, 0, 0.5);
            }

            .sales {
              background: rgba(0, 0, 0, 0.5);
              position: absolute;
              width: 100%;
              bottom: 0;
              left: 0;
              color: #fff;
              margin: 0;
              padding: 10px;
            }
          }

          .list-text-box {
            padding: 10px;

            span {
              font-size: 14px;
            }

            .red-font {
              color: #FF2C1E;
            }

            .cost-price {
              font-size: 14px;
              // margin-top: 20px;
              display: inline-block;

              &>span {}
            }
          }

          .add-btn-box {
            bottom: 0;
            width: 100%;
            background: white;
            padding: 10px;

            .addBtn {
              display: flex;
              justify-content: center;
              color: white;

              span {
                width: 90%;
                border-radius: 20px;
                text-align: center;
              }
            }
          }
        }
      }
    }
  }

  .pagination {

    /deep/ .el-pager li,
    /deep/ .btn-prev,
    /deep/ .btn-next {}
  }

  .dialog-sort {
    /deep/ .el-dialog__title {}

    /deep/ .el-dialog {}
  }

  .no-data-box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%), translateY(-50%);
  }

  .pic-sup {
    position: absolute;
    width: 56px !important;
    height: 56px !important;
    right: 10px;
    top: 10px;
  }
</style>
